package com.dailybing.ui;

import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.bingarchive.PublicUtil;
import com.bingarchive.view.BingImageView;
import com.dailybing.MainActivity;
import com.dailybing.R;
import com.dailybing.ViewActivity;

public class BingImageViewAdapter extends BaseAdapter implements View.OnClickListener {

	Context mContext;
	LayoutInflater mInflater = null;
	int mntResourceID = 0;
	int mntYear = 0;
	int mntMonth = 0;
	
	public BingImageViewAdapter(Context context, int ntResourceID) {
		mContext = context;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mntResourceID = ntResourceID;
	}
	
	public void setDate(Date date) {
		mntYear = date.getYear();
		mntMonth = date.getMonth();
	}
	
	@Override
	public int getCount() {
		return 31;
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
//		Log.d("BingImageViewAdapter", "*********************");
//		Log.d("BingImageViewAdapter", "getView pos = " + position + " convertView = " + convertView);
		
		if(convertView == null) {
			convertView = mInflater.inflate(mntResourceID, parent, false);
			convertView.findViewById(R.id.bivBox).setOnClickListener(this);
		}
		
		Date _dt = new Date(mntYear, mntMonth, position + 1);
		BingImageView _biv = (BingImageView) convertView.findViewById(R.id.bivBox);
		TextView _tv = (TextView) convertView.findViewById(R.id.tvDate);
		_tv.setText(String.valueOf(position + 1));
		
//		Log.d("BingImageViewAdapter", "Day = " + _dt.getDate());
		
		if(_biv.getBitmap() != null) {
			if(PublicUtil.GetDay(_dt) == PublicUtil.GetDay(_biv.getDate())) {
//				Log.d("BingImageViewAdapter", "Has Image");
				return convertView;
			}
		}
		
		_biv.clear();
		int _ntDay = _dt.getDate();
		if (_ntDay == position + 1) {
//			Log.d("BingImageViewAdapter", "load Image");
			_biv.loadImage(_dt);
		}
		
		return convertView;
	}

	@Override
	public void onClick(View v) {
		BingImageView _biv = (BingImageView) v;
		String _stName = _biv.getName();
		if(_stName.length() > 0) {
			Intent _it = new Intent(mContext, ViewActivity.class);
			_it.putExtra("Date", _biv.getDate().getTime());
			_it.putExtra("Name", _stName);
			mContext.startActivity(_it);
		}
	}

}
